package com.waterdispenser.controller;

import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.waterdispenser.entity.TMachine;
import com.waterdispenser.entity.TStudent;
import com.waterdispenser.service.impl.TMachineServiceImpl;
import com.waterdispenser.service.impl.TStudentServiceImpl;
import com.waterdispenser.socket.SocketArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @author: yiranxiaohui
 * @project: WaterDispenser
 * @createTime: 2023/3/19 8:41
 */
@RestController
@RequestMapping("/machine")
public class MachineController {
    @Autowired
    TMachineServiceImpl tMachineService;
    @Autowired
    TStudentServiceImpl tStudentService;
    @Autowired
    SocketArray socketArray;

    Snowflake snowflake = IdUtil.getSnowflake(1, 1);

    //使用多线程，需要线程池，防止并发过高时创建过多线程耗尽资源
    private final ExecutorService threadPool = Executors.newCachedThreadPool();

    @PutMapping("/switch")
    public SaResult Switch(@RequestBody TMachine temp){
        TMachine tMachine = tMachineService.getById(temp.getId());
        Socket socket = socketArray.getSocketHashMap().get(tMachine.getLocalIp());
        Runnable runnable = () -> {
            try(OutputStream out = socket.getOutputStream()){
//                String now = LocalDateTime.now().toString();
//                System.out.println("bytes = " + Byte.parseByte(now));
                out.write(new byte[]{1});
//                out.write(Byte.parseByte(now));
                System.out.println("发送成功！");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        };
        //接收线程返回结果
        Future future = threadPool.submit(runnable);
        System.out.println(future);
        if(tMachine == null) return SaResult.error("执行失败：机器ID不存在");
        tMachine.setState(temp.getState());
        boolean update = tMachineService.updateById(tMachine);
        if(update) return SaResult.ok("执行成功：机器打开成功！");
        else return SaResult.ok("执行成功：机器关闭成功！");
    }

    @PostMapping("/add")
    public SaResult AddMachine(@RequestBody TMachine tMachine){
        tMachine.setId(snowflake.nextId());
        boolean save = tMachineService.save(tMachine);
        if(save) return SaResult.ok("添加机器成功！");
        else return SaResult.error("添加机器失败！");
    }

    @GetMapping("/list")
    public SaResult MachineList(){
        return SaResult.get(200,"查询成功",tMachineService.list());
    }

    @GetMapping("/info/{id}")
    public SaResult Machine(@PathVariable Integer id){
        return SaResult.get(200,"查询成功", tMachineService.getById(id));
    }

    @DeleteMapping("/del/{id}")
    public SaResult delMachine(@PathVariable Long id){
        tStudentService.remove(new QueryWrapper<TStudent>().eq("id", id));
        tMachineService.removeById(id);
        return SaResult.ok("机器删除成功！");
    }

    @PutMapping("/edit")
    public SaResult editMachine(TMachine tMachine){
        TMachine machine = tMachineService.getById(tMachine.getId());
        BeanUtil.copyProperties(tMachine, machine);
        if(tMachineService.updateById(machine)) return SaResult.ok("机器信息修改成功！");
        else return SaResult.error("机器信息修改失败");
    }

    @GetMapping("/drink/student/info/{id}")
    public SaResult matchineStateInfo(@PathVariable Long id){
        return SaResult.get(200, "该机器学生饮水日志查看成功", tStudentService.list(new QueryWrapper<TStudent>().eq("id", id).orderByDesc("num")));
    }
}
